package com.dd.cloud.common.annotate.validation.impl;

import com.dd.cloud.common.annotate.validation.FixedValue;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

/**
 * 固定值
 *
 * @author zk
 */
public class FixedValueValidation implements ConstraintValidator<FixedValue, Object> {
    private String[] strValues;
    private FixedValue fixedValue;

    @Override
    public void initialize(FixedValue fixedValue) {
        strValues = fixedValue.strValues();
        this.fixedValue = fixedValue;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (!StringUtils.isBlank(fixedValue.begin())) {
            context.unwrap(HibernateConstraintValidatorContext.class).addMessageParameter("begin", fixedValue.begin());
        }
        //能为空 实际为空
        if (!fixedValue.required() && value == null) {
            return true;
        }
        //不能为空 实际为空
        if (fixedValue.required() && value == null) {
            if (fixedValue.strValues() != null && fixedValue.strValues().length > 0) {
                context.unwrap(HibernateConstraintValidatorContext.class).addMessageParameter("value", Arrays.asList(strValues));
            }
            return false;
        }
        context.unwrap(HibernateConstraintValidatorContext.class).addMessageParameter("value", Arrays.asList(strValues));
        for (String s : strValues) {
            if (s.equals(String.valueOf(value))) {
                return true;
            }
        }
        return false;
    }

}
